package cn.kgc.util.logutil.advice;


import cn.kgc.entity.LogsInfo;
import cn.kgc.service.LogsInfoService;
import cn.kgc.util.SpringContextUtils;
import cn.kgc.util.logutil.LogInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @author YC
 * 日志增强类
 */
@Aspect
@Component
@Slf4j
public class LogAdvice {

    @Pointcut("@annotation(cn.kgc.util.logutil.LogInfo)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        long startTime = System.currentTimeMillis();
        try {
            // 前置增强
            // 执行目标方法
            return joinPoint.proceed();
        } catch (Throwable e) {
            // 异常增强
            throw new RuntimeException(e);
        } finally {
            // 最终增强
            long endTime = System.currentTimeMillis();
            saveLog(joinPoint, endTime - startTime);
        }
    }

    @Resource
    private LogsInfoService logsInfoService;

    private void saveLog(ProceedingJoinPoint joinPoint, long costTime) {
        // 从注解属性中获取目标方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        if (!method.isAnnotationPresent(LogInfo.class)) {
            return;
        }
        // 获取注解信息
        LogInfo logInfoAnnotation = method.getAnnotation(LogInfo.class);
        LogsInfo logsInfo = LogsInfo.builder()
                .moduleName(logInfoAnnotation.moduleName().getName())
                .description(logInfoAnnotation.description())
                .logType(logInfoAnnotation.logType().getType())
                .userId(0)
                .costTime(costTime)
                .operateType(logInfoAnnotation.operateType().getCode())
                .method("类：" + joinPoint.getTarget().getClass().getName() + "方法：" + method.getName())
                .requestUrl(SpringContextUtils.getHttpServletRequest().getRequestURL().toString())
                .build();
        logsInfoService.save(logsInfo);
    }

}
